#include "keybasedlistmodel.h"

#include "modelcommon.h"
#include <QDebug>

KeyBasedListModel::KeyBasedListModel(QObject *parent) :
    QAbstractListModel(parent)
{
}

QVariant KeyBasedListModel::data(const QModelIndex &index, int role) const {
    if(!index.isValid())
        return QVariant();
    QString key = list.at(index.row());
    if(role == ModelCommon::KeyRole)
        return key;
    return getDataForKey(key, index.column(), role);
}

QVariant KeyBasedListModel::headerData(int section, Qt::Orientation orientation, int role) const {
    if(section != 0 || orientation != Qt::Horizontal || role != Qt::DisplayRole)
        return QVariant();
    return tr("Name");
}

int KeyBasedListModel::rowCount (const QModelIndex &parent) const {
    return parent.isValid() ? 0 : list.size();
}

QStringList KeyBasedListModel::getOrderedKeys() const {
    return list;
}

// Protected interface

QString KeyBasedListModel::keyFromIndex(const QModelIndex& index) const {
    if(!index.isValid())
        return QString();
    return list.at(index.row());
}

void KeyBasedListModel::addKey(const QString& key) {
    int pos = list.size();
    beginInsertRows(QModelIndex(), pos, pos);
    list.append(key);
    endInsertRows();
}

void KeyBasedListModel::updateKey(const QString& oldKey, const QString& newKey) {
    int pos = list.indexOf(oldKey);
    if(pos > -1) {
        list[pos] = newKey;
        QModelIndex i = index(pos);
        emit dataChanged(i,i);
    } else
        qDebug() << "KeyBasedListModel: Attempting to update invalid key" << oldKey;
}

void KeyBasedListModel::removeKey(const QString& key) {
    int pos = list.indexOf(key);
    if(pos > -1) {
        beginRemoveRows(QModelIndex(), pos, pos);
        list.removeAt(pos);
        endRemoveRows();
    } else
        qDebug() << "KeyBasedListModel: Attempting to remove invalid key" << key;
}

void KeyBasedListModel::clearKeys() {
    int size = list.size();
    if(size > 0) {
        beginRemoveRows(QModelIndex(), 0 , size-1);
        list.clear();
        endRemoveRows();
    }
}
